package com.lin.manager.interceptor;

import com.lin.manager.common.user.UserInfoContext;
import com.lin.manager.common.user.UserInfoContextHolder;
import com.lin.manager.secure.model.SecurityUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @作者: 林江
 * @创建时间: 2024/3/20
 * @功能:
 */
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (UserInfoContextHolder.getUserInfo() == null) {
            SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            UserInfoContext context = new UserInfoContext();
            context.setUserId(securityUser.getId());
            context.setUsername(securityUser.getUsername());
            context.setNickname(securityUser.getName());
            context.setMobile(securityUser.getPhone());
            UserInfoContextHolder.setUserInfo(context);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoContextHolder.clear();
    }

}
